package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/*
类简介：

功能：

时间：2020/3/30

*/
@Service(interfaceClass = CheckGroupService.class)
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;


    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        if (checkGroupDao.ifExit(checkGroup) > 0){
            throw new RuntimeException("已经存在重复项");
        }else {
            if (checkGroupDao.add(checkGroup) == 0){
                throw new RuntimeException("添加失败，请联系管理员");
            }else {
                for (Integer checkitemId : checkitemIds) {
                    if (checkGroupDao.addKey(checkGroup.getId(),checkitemId) == 0){
                        throw new RuntimeException("添加失败，请联系管理员");
                    }
                }
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        PageHelper.startPage(queryPageBean.getCurrentPage()<0?1:queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> checkGroups;
        if (queryPageBean.getQueryString() != null){
            checkGroups = checkGroupDao.findPage("%" + queryPageBean.getQueryString().trim() + "%");
            return new PageResult(checkGroups.getTotal(),checkGroups.getResult());
        }else {
            checkGroups = checkGroupDao.findPage("%%");
            return new PageResult(checkGroups.getTotal(),checkGroups.getResult());
        }
    }

    @Override
    public CheckGroup findById(int id) {

        CheckGroup checkGroup = checkGroupDao.findById(id);
        if (checkGroup == null){
            throw new RuntimeException("数据库繁忙，稍后重试");
        }
        checkGroup.setCheckItems(checkGroupDao.findCheckitems(id));
        return checkGroup;
    }

    @Override
    public void upfata(CheckGroup checkGroup, Integer[] checkitemIds) {
        if(checkGroupDao.updata(checkGroup) == 0) {
            throw new RuntimeException("数据库异常请联系管理员");
        }
        checkGroupDao.deleteConnection(checkGroup.getId());
        for (Integer checkitemId : checkitemIds) {

            if(checkGroupDao.updataConnection(checkGroup.getId(),checkitemId) == 0) {
                throw new RuntimeException("数据库异常请联系管理员");
            }

        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }
}
